package com.phiture.erp.sale.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialResp;
import com.phiture.erp.basic.api.service.ErpAccountApi;
import com.phiture.erp.basic.api.service.ErpCustomerApi;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.common.constants.ErpNoPrefixConstants;
import com.phiture.erp.common.enums.ErpAuditStatus;
import com.phiture.erp.common.enums.ErpStockRecordBizTypeEnum;
import com.phiture.erp.common.utils.ErpNoGenerator;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleOutPageReqDTO;
import com.phiture.erp.sale.core.pojo.dto.ErpSaleOutSaveReqDTO;
import com.phiture.erp.sale.core.service.ErpSaleOrderService;
import com.phiture.erp.sale.core.service.ErpSaleOutService;
import com.phiture.erp.sale.dal.entity.ErpSaleOrderDO;
import com.phiture.erp.sale.dal.entity.ErpSaleOutDO;
import com.phiture.erp.sale.dal.entity.ErpSaleOutItemDO;
import com.phiture.erp.sale.dal.mapper.ErpSaleOutItemMapper;
import com.phiture.erp.sale.dal.mapper.ErpSaleOutMapper;
import com.phiture.erp.stock.api.pojo.req.ErpStockRecordCreateReq;
import com.phiture.erp.stock.api.service.ErpStockRecordApi;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static com.phiture.erp.common.constants.ErrorCodeConstants.*;

/**
 * @author YH
 * @date 2025/4/8
 */

@Service
@RequiredArgsConstructor
public class ErpSaleOutServiceImpl implements ErpSaleOutService {

    private final ErpSaleOrderService erpSaleOrderService;
    private final AdminUserApi adminUserApi;
    private final ErpNoGenerator erpNoGenerator;
    private final ErpSaleOutMapper erpSaleOutMapper;
    private final ErpSaleOutItemMapper erpSaleOutItemMapper;
    private final ErpMaterialApi erpMaterialApi;
    private final ErpCustomerApi erpCustomerApi;
    private final ErpAccountApi erpAccountApi;
    private final ErpStockRecordApi stockRecordApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSaleOut(ErpSaleOutSaveReqDTO createReqDTO) {
        // 1.1 校验销售订单已审核
        ErpSaleOrderDO saleOrder = erpSaleOrderService.validateSaleOrder(createReqDTO.getOrderId());
        // 1.2 校验出库项的有效性
        List<ErpSaleOutItemDO> saleOutItems = validateSaleOutItems(createReqDTO.getItems());
        // 1.3 校验结算账户
        erpAccountApi.validateAccount(createReqDTO.getAccountId());
        // 1.4 校验销售人员
        if (createReqDTO.getSaleUserId() != null) {
            adminUserApi.validateUser(createReqDTO.getSaleUserId());
        }
        // 1.5 生成出库单号，并校验唯一性
        String no = erpNoGenerator.generate(ErpNoPrefixConstants.SALE_OUT_NO_PREFIX);
        validateSaleOutNo(no);

        // 2.1 插入出库
        ErpSaleOutDO saleOut = BeanUtils.toBean(createReqDTO, ErpSaleOutDO.class, in -> in
                        .setNo(no).setStatus(ErpAuditStatus.PROCESS.getStatus()))
                .setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
        calculateTotalPrice(saleOut, saleOutItems);
        erpSaleOutMapper.insert(saleOut);
        // 2.2 插入出库项
        saleOutItems.forEach(o -> o.setOutId(saleOut.getId()));
        erpSaleOutItemMapper.insertBatch(saleOutItems);

        // 3. 更新销售订单的出库数量
        updateSaleOrderOutCount(createReqDTO.getOrderId());
        return saleOut.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleOut(ErpSaleOutSaveReqDTO updateReqDTO) {
        // 1.1 校验存在
        ErpSaleOutDO saleOut = validateSaleOutExists(updateReqDTO.getId());
        if (ErpAuditStatus.APPROVE.getStatus().equals(saleOut.getStatus())) {
            throw exception(SALE_OUT_UPDATE_FAIL_APPROVE, saleOut.getNo());
        }
        // 1.2 校验销售订单已审核
        ErpSaleOrderDO saleOrder = erpSaleOrderService.validateSaleOrder(updateReqDTO.getOrderId());
        // 1.3 校验结算账户
        erpAccountApi.validateAccount(updateReqDTO.getAccountId());
        // 1.4 校验销售人员
        if (updateReqDTO.getSaleUserId() != null) {
            adminUserApi.validateUser(updateReqDTO.getSaleUserId());
        }
        // 1.5 校验订单项的有效性
        List<ErpSaleOutItemDO> saleOutItems = validateSaleOutItems(updateReqDTO.getItems());

        // 2.1 更新出库
        ErpSaleOutDO updateObj = BeanUtils.toBean(updateReqDTO, ErpSaleOutDO.class)
                .setOrderNo(saleOrder.getNo()).setCustomerId(saleOrder.getCustomerId());
        calculateTotalPrice(updateObj, saleOutItems);
        erpSaleOutMapper.updateById(updateObj);
        // 2.2 更新出库项
        updateSaleOutItemList(updateReqDTO.getId(), saleOutItems);

        // 3.1 更新销售订单的出库数量
        updateSaleOrderOutCount(updateObj.getOrderId());
        // 3.2 注意：如果销售订单编号变更了，需要更新“老”销售订单的出库数量
        if (ObjectUtil.notEqual(saleOut.getOrderId(), updateObj.getOrderId())) {
            updateSaleOrderOutCount(saleOut.getOrderId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSaleOutStatus(Long id, Integer status) {
        boolean approve = ErpAuditStatus.APPROVE.getStatus().equals(status);
        // 1.1 校验存在
        ErpSaleOutDO saleOut = validateSaleOutExists(id);
        // 1.2 校验状态
        if (saleOut.getStatus().equals(status)) {
            throw exception(approve ? SALE_OUT_APPROVE_FAIL : SALE_OUT_PROCESS_FAIL);
        }
        // 1.3 校验已退款
        if (!approve && saleOut.getReceiptPrice().compareTo(BigDecimal.ZERO) > 0) {
            throw exception(SALE_OUT_PROCESS_FAIL_EXISTS_RECEIPT);
        }

        // 2. 更新状态
        int updateCount = erpSaleOutMapper.updateByIdAndStatus(id, saleOut.getStatus(),
                new ErpSaleOutDO().setStatus(status));
        if (updateCount == 0) {
            throw exception(approve ? SALE_OUT_APPROVE_FAIL : SALE_OUT_PROCESS_FAIL);
        }

        // 3. 变更库存
        List<ErpSaleOutItemDO> saleOutItems = erpSaleOutItemMapper.selectListByOutId(id);
        Integer bizType = approve ? ErpStockRecordBizTypeEnum.SALE_OUT.getType()
                : ErpStockRecordBizTypeEnum.SALE_OUT_CANCEL.getType();
        saleOutItems.forEach(saleOutItem -> {
            BigDecimal count = approve ? saleOutItem.getCount().negate() : saleOutItem.getCount();
            stockRecordApi.createStockRecord(new ErpStockRecordCreateReq(
                    saleOutItem.getMaterialId(), saleOutItem.getWarehouseId(), count,
                    bizType, saleOutItem.getOutId(), saleOutItem.getId(), saleOut.getNo()));
        });
    }

    @Override
    public void updateSaleInReceiptPrice(Long id, BigDecimal receiptPrice) {
        ErpSaleOutDO saleOut = erpSaleOutMapper.selectById(id);
        if (saleOut.getReceiptPrice().equals(receiptPrice)) {
            return;
        }
        if (receiptPrice.compareTo(saleOut.getTotalPrice()) > 0) {
            throw exception(SALE_OUT_FAIL_RECEIPT_PRICE_EXCEED, receiptPrice,  saleOut.getTotalPrice());
        }
        erpSaleOutMapper.updateById(new ErpSaleOutDO().setId(id).setReceiptPrice(receiptPrice));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSaleOut(List<Long> ids) {
        // 1. 校验不处于已审批
        List<ErpSaleOutDO> saleOuts = erpSaleOutMapper.selectBatchIds(ids);
        if (CollUtil.isEmpty(saleOuts)) {
            return;
        }
        saleOuts.forEach(saleOut -> {
            if (ErpAuditStatus.APPROVE.getStatus().equals(saleOut.getStatus())) {
                throw exception(SALE_OUT_DELETE_FAIL_APPROVE, saleOut.getNo());
            }
        });

        // 2. 遍历删除，并记录操作日志
        saleOuts.forEach(saleOut -> {
            // 2.1 删除订单
            erpSaleOutMapper.deleteById(saleOut.getId());
            // 2.2 删除订单项
            erpSaleOutItemMapper.deleteByOutId(saleOut.getId());

            // 2.3 更新销售订单的出库数量
            updateSaleOrderOutCount(saleOut.getOrderId());
        });
    }

    @Override
    public ErpSaleOutDO getSaleOut(Long id) {
        return erpSaleOutMapper.selectById(id);
    }

    @Override
    public ErpSaleOutDO validateSaleOut(Long id) {
        ErpSaleOutDO saleOut = validateSaleOutExists(id);
        if (ObjectUtil.notEqual(saleOut.getStatus(), ErpAuditStatus.APPROVE.getStatus())) {
            throw exception(SALE_OUT_NOT_APPROVE);
        }
        return saleOut;
    }

    @Override
    public PageResult<ErpSaleOutDO> getSaleOutPage(ErpSaleOutPageReqDTO pageReqDTO) {
        MPJLambdaWrapperX<ErpSaleOutDO> query = new MPJLambdaWrapperX<ErpSaleOutDO>()
                .likeIfPresent(ErpSaleOutDO::getNo, pageReqDTO.getNo())
                .eqIfPresent(ErpSaleOutDO::getCustomerId, pageReqDTO.getCustomerId())
                .betweenIfPresent(ErpSaleOutDO::getOutTime, pageReqDTO.getOutTime())
                .eqIfPresent(ErpSaleOutDO::getStatus, pageReqDTO.getStatus())
                .likeIfPresent(ErpSaleOutDO::getRemark, pageReqDTO.getRemark())
                .eqIfPresent(ErpSaleOutDO::getCreator, pageReqDTO.getCreator())
                .eqIfPresent(ErpSaleOutDO::getAccountId, pageReqDTO.getAccountId())
                .likeIfPresent(ErpSaleOutDO::getOrderNo, pageReqDTO.getOrderNo())
                .orderByDesc(ErpSaleOutDO::getId);
        // 收款状态。为什么需要 t. 的原因，是因为联表查询时，需要指定表名，不然会报字段不存在的错误
        if (Objects.equals(pageReqDTO.getReceiptStatus(), ErpSaleOutPageReqDTO.RECEIPT_STATUS_NONE)) {
            query.eq(ErpSaleOutDO::getReceiptPrice, 0);
        } else if (Objects.equals(pageReqDTO.getReceiptStatus(), ErpSaleOutPageReqDTO.RECEIPT_STATUS_PART)) {
            query.gt(ErpSaleOutDO::getReceiptPrice, 0).apply("t.receipt_price < t.total_price");
        } else if (Objects.equals(pageReqDTO.getReceiptStatus(), ErpSaleOutPageReqDTO.RECEIPT_STATUS_ALL)) {
            query.apply("t.receipt_price = t.total_price");
        }
        if (Boolean.TRUE.equals(pageReqDTO.getReceiptEnable())) {
            query.eq(ErpSaleOutDO::getStatus, ErpAuditStatus.APPROVE.getStatus())
                    .apply("t.receipt_price < t.total_price");
        }
        if (pageReqDTO.getWarehouseId() != null || pageReqDTO.getProductId() != null) {
            query.leftJoin(ErpSaleOutItemDO.class, ErpSaleOutItemDO::getOutId, ErpSaleOutDO::getId)
                    .eq(pageReqDTO.getWarehouseId() != null, ErpSaleOutItemDO::getWarehouseId, pageReqDTO.getWarehouseId())
                    .eq(pageReqDTO.getProductId() != null, ErpSaleOutItemDO::getMaterialId, pageReqDTO.getProductId())
                    .groupBy(ErpSaleOutDO::getId); // 避免 1 对多查询，产生相同的 1
        }
        return erpSaleOutMapper.selectJoinPage(pageReqDTO, ErpSaleOutDO.class, query);
    }

    @Override
    public List<ErpSaleOutItemDO> getSaleOutItemListByOutId(Long outId) {
        return erpSaleOutItemMapper.selectListByOutId(outId);
    }

    @Override
    public List<ErpSaleOutItemDO> getSaleOutItemListByOutIds(Collection<Long> outIds) {
        if (CollUtil.isEmpty(outIds)) {
            return Collections.emptyList();
        }
        return erpSaleOutItemMapper.selectListByOutIds(outIds);
    }

    @Override
    public List<ErpSaleOutDO> getSaleOutList(Integer status, LocalDate startDate, LocalDate endDate) {
        List<ErpSaleOutDO> list = erpSaleOutMapper.selectList(
                Wrappers.lambdaQuery(ErpSaleOutDO.class)
                        .eq(ErpSaleOutDO::getStatus, status)
                        .eq(ErpSaleOutDO::getAccountCheckFlag, Boolean.FALSE)
                        .ge(startDate != null, ErpSaleOutDO::getOutTime, startDate)
                        .le(endDate != null, ErpSaleOutDO::getOutTime, endDate)
        );
        return CollUtil.isEmpty(list) ? Collections.emptyList() : list;
    }

    @Override
    public void backfillSaleOutAccountCheckFlag(Collection<Long> saleOutIds, Boolean accountCheckFlag) {
        if(CollUtil.isEmpty(saleOutIds)){
            return;
        }
        List<ErpSaleOutDO> list = saleOutIds.stream().map(saleOutId -> {
            ErpSaleOutDO saleOutDO = new ErpSaleOutDO();
            saleOutDO.setId(saleOutId);
            saleOutDO.setAccountCheckFlag(accountCheckFlag);
            return saleOutDO;
        }).collect(Collectors.toList());
        erpSaleOutMapper.updateBatch(list);
    }

    @Override
    public void updateSaleOutAccountCheckFlag(Collection<String> saleOutNos, Boolean accountCheckFlag) {
        if(CollUtil.isEmpty(saleOutNos)){
            return;
        }

        erpSaleOutMapper.update(
                Wrappers.lambdaUpdate(ErpSaleOutDO.class)
                        .set(ErpSaleOutDO::getAccountCheckFlag, accountCheckFlag)
                        .in(ErpSaleOutDO::getNo, saleOutNos)
        );
    }

    private List<ErpSaleOutItemDO> validateSaleOutItems(List<ErpSaleOutSaveReqDTO.Item> list) {
        // 1. 校验物料存在
        List<ErpMaterialResp> materialList = erpMaterialApi.validMaterialList(
                convertSet(list, ErpSaleOutSaveReqDTO.Item::getMaterialId));
        Map<Long, ErpMaterialResp> materialMap = convertMap(materialList, ErpMaterialResp::getId);
        // 2. 转化为 ErpSaleOutItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, ErpSaleOutItemDO.class, item -> {
            item.setMaterialUnitId(materialMap.get(item.getMaterialId()).getUnitId());
            item.setTotalPrice(MoneyUtils.priceMultiply(item.getMaterialPrice(), item.getCount()));
            if (item.getTotalPrice() == null) {
                return;
            }
            if (item.getTaxPercent() != null) {
                item.setTaxPrice(MoneyUtils.priceMultiplyPercent(item.getTotalPrice(), item.getTaxPercent()));
            }
        }));
    }

    private void updateSaleOrderOutCount(Long orderId) {
        // 1.1 查询销售订单对应的销售出库单列表
        List<ErpSaleOutDO> saleOuts = erpSaleOutMapper.selectListByOrderId(orderId);
        // 1.2 查询对应的销售订单项的出库数量
        Map<Long, BigDecimal> returnCountMap = erpSaleOutItemMapper.selectOrderItemCountSumMapByOutIds(
                convertList(saleOuts, ErpSaleOutDO::getId));
        // 2. 更新销售订单的出库数量
        erpSaleOrderService.updateSaleOrderOutCount(orderId, returnCountMap);
    }

    private void validateSaleOutNo(String no){
        boolean exists = erpSaleOutMapper.exists(
                Wrappers.lambdaQuery(ErpSaleOutDO.class)
                        .eq(ErpSaleOutDO::getNo, no)
                        .eq(ErpSaleOutDO::getDeleted, Boolean.FALSE)
        );
        if(exists){
            throw exception(SALE_OUT_NO_EXISTS);
        }
    }

    private ErpSaleOutDO validateSaleOutExists(Long id) {
        ErpSaleOutDO saleOut = erpSaleOutMapper.selectById(id);
        if (saleOut == null) {
            throw exception(SALE_OUT_NOT_EXISTS);
        }
        return saleOut;
    }

    private void updateSaleOutItemList(Long id, List<ErpSaleOutItemDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<ErpSaleOutItemDO> oldList = erpSaleOutItemMapper.selectListByOutId(id);
        List<List<ErpSaleOutItemDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setOutId(id));
            erpSaleOutItemMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            erpSaleOutItemMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            erpSaleOutItemMapper.deleteBatchIds(convertList(diffList.get(2), ErpSaleOutItemDO::getId));
        }
    }

    private void calculateTotalPrice(ErpSaleOutDO saleOut, List<ErpSaleOutItemDO> saleOutItems) {
        saleOut.setTotalCount(getSumValue(saleOutItems, ErpSaleOutItemDO::getCount, BigDecimal::add));
        saleOut.setTotalMaterialPrice(getSumValue(saleOutItems, ErpSaleOutItemDO::getTotalPrice, BigDecimal::add, BigDecimal.ZERO));
        saleOut.setTotalTaxPrice(getSumValue(saleOutItems, ErpSaleOutItemDO::getTaxPrice, BigDecimal::add, BigDecimal.ZERO));
        saleOut.setTotalPrice(saleOut.getTotalMaterialPrice().add(saleOut.getTotalTaxPrice()));
        // 计算优惠价格
        if (saleOut.getDiscountPercent() == null) {
            saleOut.setDiscountPercent(BigDecimal.ZERO);
        }
        saleOut.setDiscountPrice(MoneyUtils.priceMultiplyPercent(saleOut.getTotalPrice(), saleOut.getDiscountPercent()));
        saleOut.setTotalPrice(saleOut.getTotalPrice().subtract(saleOut.getDiscountPrice().add(saleOut.getOtherPrice())));
    }
}
